<?php


namespace addons\mental\model;

use app\admin\model\xlzxinfo\Xlzxinfo;
use app\common\model\WxTui;
use think\Cache;
use think\Env;
use think\Log;
use think\Model;
use addons\mental\library\Wechat;
use Hedeqiang\TenIM\IM;
use think\Db;

class WxUser extends Model
{
    // 表名
    protected $name = 'mental_wx_user';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = 'deletetime';

    // 追加属性
    protected $append = [];

    /**
     * Undocumented function
     * 微信小程序登陆第一步，需要现在后台微信配置 小程序配置里面配置好参数
     * @param [type] $code
     * @return void
     */
    public function codeToInfo($result, $type = 1)
    {
        if (isset($result['data']['unionid']) && $result['data']['unionid']) {
            $where['unionid'] = $result['data']['unionid'];
            $data['unionid']      = $result['data']['unionid'];
        } else {
            $where['openid'] = $result['data']['openid'];
        }
        $where['type'] = $type;
        $info          = $this->where($where)->find();
        if ($info) {
            //更新session_key
            $this->save(['session_key' => $result['data']['session_key']], $where);
            $wx_user_id = $info['id'];
        } else {
            $data['type']        = $type;     //类型
            $data['openid']      = $result['data']['openid'];
            $data['session_key'] = $result['data']['session_key'];
            $this->save($data);
            $wx_user_id = $this->id;
        }
        return $wx_user_id;
    }

    /**
     * Undocumented function
     * 微信小程序登陆第二步，根据微信端传过来的值解析用户数据,更新wx_user表
     * @param [type] $wx_user_id
     * @param [type] $edata
     * @param [type] $iv
     * @param integer $pid
     * @return void
     */
    public function updateWxInfo($info, $userInfo)
    {
        if (isset($userInfo['unionId']) && $userInfo['unionId']) {
            $where['unionid'] = ['eq', $userInfo['unionId']];
            $where['user_id'] =  ['neq', '0'];
            $wxUserInfo = $this->where($where)->find();
            if ($wxUserInfo) {
                $info['user_id'] = $wxUserInfo['user_id'];
                $data['user_id'] = $wxUserInfo['user_id'];
            }
        }

        if (!empty($info['user_id'])) {
            $data['user_id'] = $info['user_id'];
        }

        $data['id']       = $info['id'];
        $data['avatar']   = $userInfo['avatarUrl'];
        $data['nickname'] = $userInfo['nickName'];
        $data['gender']   = $userInfo['gender'];
        $data['language'] = $userInfo['language'];
        $data['city']     = $userInfo['city'];
        $data['province'] = $userInfo['province'];
        $data['country']  = $userInfo['country'];

        $this->save($data, ['id' => $data['id']]);

        return $info['id'];
    }

    public function updateTtInfo($param, $info)
    {
        if (!empty($info['user_id'])) {
            $data['user_id'] = $info['user_id'];
        }

        $data['id']       = $info['id'];
        $data['avatar']   = $param['avatarUrl'];
        $data['nickname'] = $param['nickName'];
        $data['gender']   = $param['gender'];
        $data['language'] = $param['language'];
        $data['city']     = $param['city'];
        $data['province'] = $param['province'];
        $data['country']  = $param['country'];

        return $this->save($data, ['id' => $data['id']]);
    }

    /**
     * Undocumented function
     * 公众号无感登陆
     * @param [type] $url
     * @return void
     */
    public function officialMiniLogin($url)
    {
        $config = get_addon_config('epay');
        $result        = [
            'status' => false,
            'data'   => '',
        ];
        $url           = urlencode($url, $scope = 'snsapi_base');
        $result['data'] = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $config['wechat']['app_id'] . "&redirect_uri=" . $url . "&response_type=code&scope=" . $scope . "&state=mental#wechat_redirect";
        return $result;
    }


    public function addUserWx($param, $user_id, $pid = 0)
    {
        $data = [];
        $result        = [
            'status' => true,
            'data'   => '',
        ];

        $data['user_id'] = $user_id ? $user_id : 0;
        if (isset($param['unionid']) && $param['unionid']) {
            $where['unionid'] = $param['unionid'];
            $data['unionid']  = $param['unionid'];
        } else {
            $where['openid'] = $param['openid'];
            $data['openid']  = $param['openid'];
        }
        $where['type'] = 2;
        $info  = $this->where($where)->find();
        if ($info) {
            $result['data'] = $info;
        } else {
            $data['type'] = 2;
            $data['avatar']   = $param['headimgurl'];
            $data['nickname'] = $param['nickname'];
            $data['gender']   = $param['sex'];
            $data['language'] = $param['language'];
            $data['city']     = $param['city'];
            $data['province'] = $param['province'];
            $data['country']  = $param['country'];
            $this->save($data);
            $data['id'] = $this->id;
            $result['data'] = $data;
        }
        return $result;
    }

    /*
     * 公众号推送订单消息
     * */
    public static function push_template_order($consult_order_id)
    {
        $consult_order = \app\admin\model\consult\Order::where(['id'=>$consult_order_id])->find();
        $user = \app\common\model\User::where('id',$consult_order['user_id'])->find();
        $xlzxinfo = Xlzxinfo::where(['id'=>$consult_order['xlzxinfo_id']])->find();
        $touser = \app\common\model\User::where('id',$xlzxinfo['user_id'])->value('official_openid');

        // $app_id = 'wx34bddd7989014148';
        // $app_secret = '59bbd61d99690e0e5e0d2b9b4cc3e8c0';
        // // 获得access_token
        // $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$app_id&secret=$app_secret";
        // $weix = file_get_contents($url);//获得网页输出
        // $obj=json_decode($weix,true );//解码
        // $access_token1= $obj['access_token'];//网页授权接口调用凭证
        // echo $access_token1."<br/>";
        // // 
        // Cache::rm("official_access_token");
        // Cache::set("official_access_token",$access_token1,7000);

        $access_token =  self::gettoken();
        // echo $access_token."<br/>";
        // exit();
        $start_time = $consult_order['start_time'];
        if(empty($consult_order['start_time'])){
            if($consult_order['consult_type']==1){
                $start_time = '文字咨询下单了,请及时联系客户';
            }
            if($consult_order['consult_type']==2){
                $start_time = '语音咨询下单了,请及时联系客户';
            }
        }
        //发送模板消息
        $fasuerl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
        $data = array(
            "touser"=>$touser,
            "template_id"=>"TkgZSwfdj7IzSQT1Qats46OPHuRjewqeLSxN5Miy454",
//            "miniprogram"=> array(
//                "appid"=>"wx170fe8ce2ce8c283",
//                "pagepath"=>"page/index"
//            ),
            "data" => array(
                "thing3" => array(
                    "value"=>$xlzxinfo['full_name'],
                    "color"=>"#173177"
                ),
                "thing6" => array(
                    "value"=>$start_time,
                    "color"=>"#000000"
                ),
                "thing12" => array(
                    "value"=>$user['nickname'],
                    "color"=>"#000000"
                ),
            )
        );
        $params = json_encode($data);
        Log::info($params);
        $res=curlPost($fasuerl,$params);
        Log::info('公众号推送订单消息');
        Log::info($res);
        return true;
    }

    /*
     * 公众号推送IM消息
     * */
    public static function push_template_im($touser,$fromuser,$text)
    {

//        $app_id = 'wx34bddd7989014148';
//        $app_secret = '59bbd61d99690e0e5e0d2b9b4cc3e8c0';
//
//        //获得access_token
//        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$app_id&secret=$app_secret";
//        $weix = file_get_contents($url);//获得网页输出
//        $obj=json_decode($weix,true );//解码
////        var_dump($obj);
//        $access_token= $obj['access_token'];//网页授权接口调用凭证
        $access_token = self::gettoken();
        //发送模板消息
        $fasuerl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;

        $text = mb_substr($text,0,5,'UTF-8').'...';
        $data = array(
            "touser"=>$touser['official_openid'],
            "template_id"=>"TkgZSwfdj7IzSQT1Qats46OPHuRjewqeLSxN5Miy454",
//            "miniprogram"=> array(
//                "appid"=>"wx170fe8ce2ce8c283",
//                "pagepath"=>"page/index"
//            ),
            "data" => array(
                "thing3" => array(
                    "value"=>$touser['full_name'],
                    "color"=>"#173177"
                ),
                "thing6" => array(
                    "value"=>$text,
                    "color"=>"#000000"
                ),
                "thing12" => array(
                    "value"=>$fromuser['nickname'],
                    "color"=>"#000000"
                ),
            )
        );

        $params = json_encode($data);
        Log::info('发送参数');
        Log::info($params);
        $res=curlPost($fasuerl,$params);
        Log::info('公众号推送IM消息');
        Log::info($res);
        return true;
    }


    /**
     * 用户发送第一条消息后,给咨询师发送公众号消息
     * [push_template_messsage description]
     * @param  [type] $user [description]
     * @return [type]       [description]
     */
    public static function push_template_messsage($xlzxsid,$userid,$content){        
        $touser = \app\common\model\User::where('id',$xlzxsid)->value('official_openid');
        $user = \app\common\model\User::where('id',$userid)->find();

        $access_token =  self::gettoken();
        
    
        //发送模板消息
        $fasuerl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
        $data = array(
            "touser"=>$touser,
            "template_id"=>"dFPpuSyVQN56J5OfEEEYzlPTKExgkxTXBwNuMzRGdnQ",
            "data" => array(
                "thing3" => array(
                    "value"=>$user['nickname'],
                    "color"=>"#173177"
                ),
                "thing4" => array(
                    "value"=>'收到新的咨询消息',
                    "color"=>"#000000"
                ),
                
            )
        );
        $params = json_encode($data);
        $arr = [
            'name'=>'公众号推送用户咨询消息',
            'content'=>$params,
            'create_time'=>time(),
        ];
        Db::name('message_log')->insert($arr);
        Log::info('发送参数');
        Log::info($params);
        $res=curlPost($fasuerl,$params);
        Log::info('公众号推送用户沟通消息');
        Log::info($res);
        return true;

    }


    /**
     * 定期更改im下的头像
     * [im_update description]
     * @param  [type] $params [description]
     * @return [type]         [description]
     */
    public static function im_update($params = null){
        $config = [
            'sdk_app_id' => Env::get('im.sdk_app_id', ''),
            'identifier' => Env::get('im.identifier', ''),
            'secret_key' => Env::get('im.secret_key', ''),
        ];
        //注册腾讯IM
        $data = [
            'From_Account' => (string)$params['id'],
            'ProfileItem' => [
                ['Tag' => 'Tag_Profile_IM_Nick', 'Value' => $params['nickname']],
                ['Tag' => 'Tag_Profile_IM_Image', 'Value' => compatImage($params['avatar'])],
            ],
        ];
        $im = new IM($config);
        $res = $im->send('profile','portrait_set',$data);
        Log::info('IM用户修改资料：'.$params['id']);
        Log::info($res);
        return true;
    }


    /**
     * 每次打开聊天窗口，给发送消息
     * [everyIm description]
     * @return [type] [description]
     */
    public static function everyIm($xlzxsid,$userid,$content){
        // $url = 'https://console.tim.qq.com/v4/openim/sendmsg?sdkappid=1400794757&identifier=admin&usersig=xxx&random=99999999&contenttype=json';
        $config = [
            'sdk_app_id' => Env::get('im.sdk_app_id', ''),
            'identifier' => Env::get('im.identifier', ''),
            'secret_key' => Env::get('im.secret_key', ''),
        ];
        $params = [
            'SyncOtherMachine' => 1, // 消息不同步至发送方
            'From_Account' => (string)$xlzxsid,
            'To_Account' => (string)$userid,
            'MsgRandom' => time(),
            'MsgTimeStamp' => time(),
            'MsgBody' => [
                [
                    'MsgType' => 'TIMTextElem',
                    'MsgContent' => [
                        'Text' => $content
                    ]
                ]
            ]
        ];
        $im = new IM($config);
        $res = $im->send('openim','sendmsg',$params);
        return $res;
    }

    private static function  getAccessToken($force = false) {

        $access_token =Cache::get("official_access_token");//存入redis，这里要结合自己的项目，对redis或者memcahe进行设置
        Log::info('redis_official:'.$access_token);
        if(!$access_token || $force){
            $appId = 'wx34bddd7989014148';
            $appSecret = '59bbd61d99690e0e5e0d2b9b4cc3e8c0';
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appId."&secret=".$appSecret;
            $data = json_decode(getJson($url),true);
            Log::info('token:'.json_encode($data,true));
            if(isset($data['access_token']) && $data['access_token'] != ''){
                Cache::rm("official_access_token");
                Cache::set("official_access_token",$data['access_token'],7000);
                $access_token=$data['access_token'];
            }else{
                return false;
            }
        }
        return $access_token;
    }

    public static function gettoken()
    {
        return self::getAccessToken();
    }
}
